<template>
  <div class="search">
<form action="/">
  <van-search
    v-model="value"
    show-action
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    background="#3296fa"
    @focus="isfocus = false"
  />
</form>
<SearchResult v-if="isfocus" :val="value"></SearchResult>
<SearchSuggestion v-else-if="value" :searchText="value"  @search="onSearch"></SearchSuggestion>
<SearchHistory @search="onSearch" v-else :val="SearchHistory" @removeAll="SearchHistory = []" ></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  data () {
    return {
      value: '',
      isfocus: false,
      SearchHistory: getItem('HistoryData') || []
    }
  },
  methods: {
    onSearch (text) {
      this.isfocus = true
      this.value = text
      const index = this.SearchHistory.indexOf(text)
      if (index !== -1) {
        this.SearchHistory.splice(index, 1)
      }
      this.SearchHistory.unshift(text)
    },
    onCancel () {
      this.$router.back()
    },
    isfocusFn () {
      this.isfocus = true
    }
  },
  watch: {
    SearchHistory (val) {
      setItem('HistoryData', val)
    }
  }
}
</script>

<style scoped lang="less">
.search {
    padding-top: 106px;
    .van-search {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
.van-search__action {
    color: #fff;
  }
  }
</style>
